<template>
	<view class="post-detail">
		<u-navbar back-icon-color="#000" title=" ">
			<view @click="goUser" class="row-center">
				<view v-if="post.user.avatar" class="avatar-image" :class="{ 'avatar-show':showAvatar }">
					<u-image width="72" height="72" shape="circle" :src="post.user.avatar"></u-image>
				</view>
				<view class="ml20 nickName" v-if="post.user.nickname">
					{{post.user.nickname}}
				</view>
			</view>
		</u-navbar>
		<mescroll-body height="200rpx" ref="mescrollRef" :up="upOption" @init="mescrollInit" @down="downCallback"
			@up="upCallback">
			<view v-if="post.id" class="comment-area" id="comment-up-area">
				<swiper :style="{ height: swiperHeight + 'px' }" mode="rect" indicator-dots="true"
					indicator-color="#fff" indicator-active-color="#FF5E61">
					<swiper-item v-for="(img, index) in post.imgs" :key="index">
						<image mode="aspectFit" @click="onPreview" :src="img" :style="{ height: swiperHeight + 'px' }"
							style="width: 100%;"></image>
					</swiper-item>
				</swiper>
				<view class="main-body ml20 mr20">
					<view class="title bold">
						{{ post.title }}
					</view>
					<view class="content xs mt20">
						<rich-text :nodes="post.description"></rich-text>
					</view>
					<view class="row-center mt30 product-wrapper">
						<template v-if="post.products[0].id">
							<navigator class="goods-item row-center flex1" hover-class="none"
								:url="'/pages/goods_details/goods_details?id=' + post.products[0].id">
								<view class="">
									<custom-image width="80rpx" height="80rpx" radius="4rpx" lazy-load
										:src="post.products[0].pics[0]">
									</custom-image>
								</view>
								<view class="prodcut-title flex1 line2">
									{{post.products[0].title}}
								</view>
							</navigator>
							<view class="column-center"
								@click.stop="goto('/pages/goods_details/goods_details?action=singleBuy&id=' + post.products[0].id)">
								<view class="purchase-button row-center">
									购买
								</view>
							</view>
						</template>
					</view>
				</view>
			</view>
			<view class="comment-top">
				<view class="title"> 评论
					<text v-if="commentList.length">
						{{post.comment_num}}
					</text>
				</view>
			</view>
			<StarCommentList :list="commentList" :post_id="post.id" :option="commentOption" :my_user="userInfo"
				@selectComment="selectComment" @clickUserAvatar="clickCommentUserAvatar"
				@clickUserNickname="clickCommentUserNickname" @clickReplyUserNickname="clickCommentReplyUserNickname"
				@longpressComment="longpressComment" @toggleLike="toggleCommentLike"></StarCommentList>
		</mescroll-body>
		<view v-if="post.id">
			<StarCommentReply :isLogin="isLogin" ref="starCommentReplyRef" :post="post" :option="replyOption"
				@sendComment="sendComment">
			</StarCommentReply>
		</view>
	</view>
</template>

<script>
	import {
		getPost,
		getComment,
		addComment,
		likeCommentPost,
		updateShareNum
	} from "@/api/discover";
	import MescrollMixin from "@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js";
	import StarPostItem from "@/uni_modules/star-community/components/star-post-item/star-post-item.vue";
	import StarCommentList from "@/uni_modules/star-community/components/star-comment-list/star-comment-list.vue";
	import StarCommentReply from "@/uni_modules/star-community/components/star-comment-reply/star-comment-reply.vue";
	import {
		toLogin
	} from "@/utils/login";
	import {
		mapGetters,
		mapMutations
	} from 'vuex'
	import PageExposure from "@/mixins/page_exposure.js"

	export default {
		mixins: [MescrollMixin, PageExposure], // 使用mixin
		components: {
			StarPostItem,
			StarCommentList,
			StarCommentReply,
		},
		computed: {
			...mapGetters(['userInfo', 'isLogin']),
		},
		async onShareAppMessage() {
			updateShareNum({
				id: this.post.id
			})
			return {
				title: this.post.title,
				imageUrl: this.post.imgs[0],
				path: '/social/pages/post-detail/post-detail?id=' + this.post.id
			};
		},
		data() {
			return {
				selectedTab: "recommend", // 默认选择推荐标签
				postOption: {
					showView: true,
				},
				commentOption: {
					showDelete: true,
				},
				postId: undefined,
				replyOption: {
					imgMaxCount: 9, // 选择图片最大数量
				},
				upOption: {
					isBounce: false,
					noMoreSize: 4, // 如果列表已无数据,可设置列表的总数量要大于半页才显示无更多数据;避免列表数据过少(比如只有一条数据),显示无更多数据会不好看; 默认5
					toTop: {
						bottom: "320rpx",
						safearea: true,
					},
				},
				loaded: false,
				swiperHeight: 100, // 初始加载高度
				post: {},
				commentList: [],
				location: {}
			};
		},
		onLoad(option) {
			this.getPostItem({
				id: option?.id
			});
			this.postId = option?.id
			// 拉取帖子数据

			// 是否自动滑动至评论区，option?.comment === 'yes'
			if (option?.comment === "yes") {
				// 等待dom渲染完毕，才能获取节点信息
				setTimeout(() => {
					this.goArea("#comment-up-area"); // 自动滑动至评论区
					this.$refs.starCommentReplyRef.focus = true; // 评论框自动聚焦
				}, 300);
			}
		},
		async onShow() {
			this.location = await this.getLocation();
		},
		methods: {
			...mapMutations(['UPDATEPOSTLIKES']),
			onPurchase() {},
			// 下拉刷新的回调
			downCallback() {
				// 这里加载你想下拉刷新的数据, 比如刷新轮播数据
				// loadSwiper();
				// 下拉刷新的回调,默认重置上拉加载列表为第一页 (自动执行 page.num=1, 再触发upCallback方法 )
				this.mescroll.resetUpScroll();
			},
			// 上拉加载的回调: 其中page.num:当前页 从1开始, page.size:每页数据条数,默认10
			async upCallback(page) {
				try {
					// 请求数据列表
					let list = await this.getCommentList(page);
					// 设置列表数据
					if (page.num === 1) this.commentList = []; // 如果是第一页需手动制空列表
					this.commentList = [...this.commentList, ...list]; // 追加新数据
					// 联网成功的回调,隐藏下拉刷新和上拉加载的状态
					this.mescroll.endSuccess(list.length);
				} catch (err) {
					console.log(err);
				}
			},
			// 获取评论列表
			async getCommentList(page) {
				return await getComment({
					page: page.num,
					pagesize: page.size,
					id: this.postId
				});
			},
			async getPostItem(params) {
				const {
					s,
					d
				} = await getPost({
					pagesize: 1,
					page: 1,
					...params
				});
				const {
					data,
					num
				} = d || {}
				if (s === 0) {
					const _data = data?.data || []
					this.UPDATEPOSTLIKES(_data)
					this.post = _data[0] || {}
					this.updateHeight(this.post.imgs)
					return this.post
				}
				return {}
			},
			async replyComment(params) {
				// 回复功能
				return await addComment({
					...(params || {}),
					...this.location,
					id: this.postId
				});
			},
			async getLocation() {
				const [error, res] = await uni.getLocation({
					type: 'gcj02'
				})
				if (error) {
					return {}
				}
				return {
					lat: res?.latitude,
					lon: res?.longitude
				}
			},
			updateHeight(imgs) {
				if (!imgs || imgs.length === 0) return;

				// 获取屏幕宽度
				const systemInfo = uni.getSystemInfoSync();
				this.screenWidth = systemInfo.screenWidth;

				let loadedImages = 0;
				let maxImgHeight = 0; // 保存最大图片高度
				let failedImages = 0; // 记录加载失败的图片数量

				// 计算轮播图的高度。以便完全将帖子全部展示出来
				imgs.forEach((imgUrl) => {
					uni.getImageInfo({
						src: imgUrl,
						success: (image) => {
							const imgWidth = image.width;
							const imgHeight = image.height;
							const imgRatio = imgWidth / this.screenWidth;
							let displayHeight;

							if (imgRatio >= 1) {
								displayHeight = imgHeight / imgRatio;
							} else {
								displayHeight = imgHeight * imgRatio;
							}

							// 更新最大高度
							if (displayHeight > maxImgHeight) {
								maxImgHeight = displayHeight;
							}

							loadedImages += 1;
							checkIfAllImagesProcessed();
						},
						fail: (error) => {
							console.error("Image loading failed:", error);
							failedImages += 1;
							checkIfAllImagesProcessed();
						}
					});
				});

				const checkIfAllImagesProcessed = () => {
					// 当所有图片都已处理（无论成功还是失败）时，更新swiperHeight
					if (loadedImages + failedImages === imgs.length) {
						this.loaded = true;
						this.swiperHeight = Math.max(100, Math.min(600, maxImgHeight));
					}
				};
			},
			// 自动滑动至某元素，如评论区
			goArea(selector) {
				uni
					.createSelectorQuery()
					.select(selector)
					.boundingClientRect((res) => {
						uni.pageScrollTo({
							scrollTop: res.height,
						});
					})
					.exec();
			},
			// 选中帖子
			selectPost(post) {
				// 重置评论框
				this.$refs.starCommentReplyRef.resetCommentReply();
				this.$refs.starCommentReplyRef.focus = true;
			},

			// 点击帖子用户头像
			clickPostUserAvatar(post) {
				this.goto(`../homepage/homepage?id=${post.user_id}`);
			},
			// 点击贴子用户昵称
			clickPostUserNickname(post) {
				this.goto(`../homepage/homepage?id=${post.user_id}`);
			},
			// 选中评论
			selectComment(comment) {
				// 重置评论框
				this.$refs.starCommentReplyRef.resetCommentReply();
				if (comment.father_id) {
					this.$refs.starCommentReplyRef.to_father_id = comment.father_id;
					this.$refs.starCommentReplyRef.to_child_id = comment.id;
				} else {
					this.$refs.starCommentReplyRef.to_father_id = comment.id;
				}
				this.$refs.starCommentReplyRef.to_user_id = comment.user.id;
				this.$refs.starCommentReplyRef.placeholder = `回复：${comment.user.nickname}`;
				this.$refs.starCommentReplyRef.focus = true;
			},
			// 发送评论
			async sendComment(comment) {
				let vuex_user = this.userInfo; // 从缓存获取我的用户信息
				// 必要信息，请替换成实际值
				let myComment = {
					status: 1, // 0 审核中 1 正常 2 审核不通过 3 已删除 4 已违规
					commentCount: 0,
					commentList: [],
					content: comment.content,
					created_at: Date.now(),
					id: Date.now().toString(),
					// imgList: comment.imgList, // 在此之前请将临时路径替换成线上路径
					like_num: 0,
					post_id: this.post.id,
					user_id: vuex_user.id,
				};

				// 需要回复的父评论
				let fatherComment,
					fatherCommentIndex = -1;
				fatherCommentIndex = this.commentList.findIndex(
					(fatherComment) => fatherComment.id === comment?.to_father_id
				); // 父评论下标
				if (fatherCommentIndex > -1) {
					fatherComment = this.commentList[fatherCommentIndex];
				}

				// // 需要回复的子评论
				// let childComment,
				// 	childCommentIndex = -1;
				// if (fatherCommentIndex > -1) {
				// 	let childCommentList = fatherComment.commentList || [];
				// 	childCommentIndex = childCommentList.findIndex(
				// 		(childComment) => childComment.id === comment?.to_child_id
				// 	);
				// 	if (childCommentIndex > -1) {
				// 		childComment = fatherComment.commentList[childCommentIndex];
				// 	}
				// }
				// // 回复子评论
				// if (fatherComment && childComment) {
				// 	myComment.father_id = fatherComment.id;
				// 	myComment.reply_child_id = childComment.id;

				// 	const success = await this.replyComment(myComment)
				// 	if (!success) return
				// 	myComment.avatar = vuex_user.avatar;
				// 	myComment.nickname = vuex_user.nickname;
				// 	myComment.isNewComment = true; // 优化显示体验，请勿将此字段添加至数据库
				// 	myComment.replyChildComment = childComment;
				// 	this.commentList[fatherCommentIndex].commentList.splice(
				// 		childCommentIndex + 1,
				// 		0,
				// 		myComment
				// 	);
				// }
				// 回复父评论
				// else 
				if (fatherComment) {
					myComment.father_id = fatherComment.id;
					myComment.parent_comment = fatherComment;
					const _comment = await this.replyComment(myComment)
					if (!_comment) return
					myComment.user = {
						avatar: vuex_user.avatar,
						nickname: vuex_user.nickname
					}
					myComment.province = _comment.province
					this.commentList.unshift(myComment);

					// myComment.isNewComment = true; // 优化显示体验，请勿将此字段添加至数据库
					// const isNewComment = !this.commentList[fatherCommentIndex].commentList
					// // this.commentList[fatherCommentIndex].commentList.unshift(myComment);
					// if (isNewComment) {
					// 	this.commentList[fatherCommentIndex].commentList = [myComment];
					// } else {
					// 	this.commentList[fatherCommentIndex].commentList.unshift(myComment);
					// }
				}
				// 回复帖子
				else {
					const _comment = await this.replyComment(myComment)
					if (!_comment) return
					myComment.user = {
						avatar: vuex_user.avatar,
						nickname: vuex_user.nickname
					}
					myComment.province = _comment.province
					this.commentList.unshift(myComment);
				}
				// 重置评论框
				this.$refs.starCommentReplyRef.resetCommentReply();
				this.$refs.starCommentReplyRef.placeholder = comment.placeholder; // 延用回复占位符
				this.$refs.starCommentReplyRef.to_father_id = comment.to_father_id; // 延用回复父评论
				this.$refs.starCommentReplyRef.to_child_id = comment.to_child_id; // 延用回复子评论
				this.$refs.starCommentReplyRef.to_user_id = comment.to_user_id; // 延用回复谁
				uni.showToast({
					title: "发送成功",
				});
			},
			// 长按评论
			longpressComment(comment) {

				// this.showCommentMoreActionSheet(comment);
			},
			// 点击评论用户头像
			clickCommentUserAvatar(comment) {
				this.goto(`../homepage/homepage?id=${comment.user_id}`);
			},
			// 点击评论用户昵称
			clickCommentUserNickname(comment) {
				this.goto(`../homepage/homepage?id=${comment.user_id}`);
			},
			// 点击评论回复用户昵称
			clickCommentReplyUserNickname(comment) {
				this.goto(`../homepage/homepage?id=${comment.parent_comment.user.id}`);
			},
			onPreview(index) {
				uni.previewImage({
					current: index,
					urls: this.post.imgs,

				});
			},
			// 点击喜欢评论
			toggleCommentLike(comment, isLiked) {
				if (!this.isLogin) {
					return toLogin()
				}
				likeCommentPost({
					id: comment.id,
					action: isLiked ? 1 : 0
				})
			},
			// 显示帖子更多操作菜单选项
			showPostMoreActionSheet() {
				uni.showActionSheet({
					itemList: ["举报"],
					success: (res) => {
						console.log("选中了第" + (res.tapIndex + 1) + "个按钮");
						uni.showToast({
							title: "举报成功",
						});
					},
					fail: (res) => {
						console.log(res.errMsg);
					},
				});
			},
			// 显示帖子更多操作菜单选项
			showCommentMoreActionSheet(comment) {
				uni.showActionSheet({
					itemList: ["举报"],
					success: (res) => {
						console.log("选中了第" + (res.tapIndex + 1) + "个按钮");
						uni.showToast({
							title: "举报成功",
						});
					},
					fail: (res) => {
						console.log(res.errMsg);
					},
				});
			},
			goUser() {
				uni.navigateTo({
					url: `/social/pages/homepage/homepage?id=${this.post.user_id}`,
				});
			},
			goto(url) {
				if (!this.isLogin) {
					return toLogin()
				}
				uni.navigateTo({
					url,
				});
			},
		},
	};
</script>

<style scoped lang="scss">
	.nickname {
		font-family: Roboto;
		color: #000000;
		font-size: 32rpx;
		margin-left: 30rpx;
	}

	.comment-area {
		padding-top: 10rpx;
		background-color: #fff;
	}

	.purchase-button {
		width: 124rpx;
		height: 56rpx;
		border-radius: 32rpx;
		background-color: #FF5E61;
		color: #fff;
		font-size: 24rpx;
		line-height: 0;
		font-weight: 500;
	}

	.product-wrapper {
		padding-bottom: 35rpx;
		border-bottom: 2rpx solid #eee;
	}

	.post-detail {
		padding-bottom: 120rpx; // 评论框底部安全距离

		.main-body {}

		.title {
			font-family: HYQiHei 65S;
			color: #000000;
			font-size: 32rpx;
			margin-top: 24rpx;
		}

		.prodcut-title {
			margin: 0 40rpx 0 18rpx;

		}

		.content {
			color: rgb(44, 44, 44);
			font-size: 28rpx;
			line-height: 55rpx;
			white-space: pre-wrap;
		}

		.comment-top {
			padding: 35rpx 20rpx 20rpx;
			width: 100%;
			box-sizing: border-box;
			display: inline-flex;
			align-items: center;
			justify-content: space-between;
			background: #fff;

			.title {
				margin-top: 0;
				font-weight: bold;
			}

			.tab {
				display: flex;

				.tab-item {
					padding: 10rpx;

					&.active {
						font-weight: 700;
					}
				}
			}
		}
	}
</style>